$(function () {
    layui.use(['form', 'layer', 'jquery'],
        function () {
            $ = layui.jquery;
            var form = layui.form,
                layer = layui.layer;
            //得到id后，根据id查询数据库，赋值给前端表单
            let userId = sessionStorage.getItem("userId")
            $.ajax({
                url: '/back/FindUserById',
                data: {id: userId},
                type: 'get',
                dataType: 'json',
                success: function (res) {
                    //赋值
                    console.log(res);
                    setData(res.data);
                }
            })

            function setData(data) {
                form.val('form', {
                    "username": data.username // "name": "value"
                    , "sex": data.sex
                    , "age": data.age
                    , "phone": data.phone
                    , "email": data.email
                    , "address": data.address
                    , 'remark': data.remark
                });
                $("input[type=radio][name=enable][value=" + data.enable + "]").attr("checked", "checked");
                form.render();//重新渲染表单
            }

            //自定义验证规则
            form.verify({

                username: [/^[\u4e00-\u9fa5a-zA-Z0-9]{2,12}$/, "用户名只能是字符加数字必须2到16位"],
                age:[/^(?:[1-9][0-9]?|1[01][0-9]|120)$/,"年龄只能是1-120的整数"],
                phone: [/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,"手机号格式不正确"],
               address:[/^[\u4E00-\u9FA5A-Za-z0-9]+$/,"地址只能包含中文、英文或数字"], //中文、英文、数字但不包括下划线等符号
            });

            //监听提交
            form.on('submit(update)',
                function (data) {
                    data = data.field;
                    // console.log(data);
                    //根据id修改
                    data.id = sessionStorage.getItem("userId")//修改servlet里没有传id，需获取从user-list.js传过来的id
                    $.ajax({
                        url: '/back/UpdateUser',
                        data: data,
                        type: 'post',
                        dataType: 'json',
                        success: function (res) {
                            if (res.count > 0) {
                                //发异步，把数据提交给java
                                layer.alert(res.msg, {
                                        icon: 6
                                    },
                                    function () {
                                        //关闭当前frame
                                        xadmin.close();

                                        // 可以对父窗口进行刷新
                                        xadmin.father_reload();
                                    });
                            } else {
                                layer.alert(res.msg)
                            }
                        }
                    })
                    return false;
                });

        });
})